/*
 * 组件注释
 * @Author: machinist_wq
 * @Date: 2022-09-02 21:29:42
 * @LastEditors: machinist_wq
 * @LastEditTime: 2022-09-02 22:02:26
 * @Description: 倒计时hook
 * 人生无常！大肠包小肠......
 */
"use strict";
import { useState, useEffect, useRef, FC, SetStateAction } from "react";

/*
 * 组件注释
 * create by wuqiong
 * creation time 2021/06/29
 * 倒计时
 * */
interface Iprops {
  id?: "string";
}
type CountType = number | string;

const Index = (props: Iprops): [CountType, (count: CountType) => void] => {
  const id = props?.id || "countdown";
  const [countDownTime, setcountDownTime] = useState<CountType>(0);
  const timer = useRef<NodeJS.Timeout | null>(null);

  const countDown = (count: CountType) => {
    timer.current = setTimeout(() => {
      --(count as number);
      setcountDownTime(count);
      if (count! >= 1) {
        sessionStorage.setItem(id, count as string);
        countDown(count);
      } else {
        sessionStorage.removeItem(id);
        setcountDownTime(0);
      }
    }, 1000);
  };

  useEffect(() => {
    const count = sessionStorage.getItem(id);
    if (count && (count as unknown as number) > 0) {
      countDown(count);
    }
    return () => {
      sessionStorage.removeItem(id);
      clearInterval(timer.current as NodeJS.Timeout);
    };
  }, []);
  return [countDownTime, countDown];
};
export default Index;
